<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    {% load  static %}
    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
</head>
<body>
    <div class="wrapper">
        <form>
            {% csrf_token %}
            <div>
                用户名: <input type="text" name="userName">
                <span class="usererr"></span>
            </div>
            <div>
                密码: <input type="text" name="password">
                <span class="pwderr"></span>
            </div>  
            <div>
                email: <input type="text" name="email">
            </div> 
            <div>
                角色:
                <input type="radio" name="userType" value="0">后台
                <input type="radio" name="userType" value="1">前台
            </div> 
            <div>
                <input type="button" value="注册">
            </div>
        </form>
    </div>
    <script>
        $(function(){
            let _password=$('input[name=password]')
            let _pwderr=$('.pwderr')
            _password.blur(function(){
                checkPassword()
            })
            
            //检测密码
            function checkPassword(){
                _pwderr.html('')  //重新验证前清空提示
                let password=_password.val()
                if(!password){
                    _pwderr.html('密码不为空')
                    return false
                }
                let reg=/^\d{3,6}$/
                if(!reg.test(password)){
                    _pwderr.html('密码是3-6位数字')
                    return false
                }
                return true
            }
            let _userName=$('input[name=userName]')
        let _usererr=$('.usererr')
        _userName.blur(function(){
            checkUserName()
        })
         //检测密码
        function checkUserName(){
            _usererr.html('')  //重新验证前清空提示
            let userName=_userName.val()
            if(!userName){
                _usererr.html('用户名不能为空')
                return false
            }
            let reg=/^\w{2,6}$/
            if(!reg.test(userName)){
                _usererr.html('用户名是2-6位字母数字下划线组合')
                return false
            }
            return true
        }
        $(':button').click(function (){
            if(checkUserName()&checkPassword()){
                //发送ajax提交
                //获取所有表单参数
                let data=$('form').serialize()
                $.post('/news/register2/',data)
                .then(res=>{
                    if(res.code==200){
                        location.href='/news/login2/'
                    }
                    alert(res.msg)
                })
                    .catch(err=>console.log(err)) //失败响应结果
            }else{
                alert('请检查信息')
            }
            
        })
        })
    </script>
</body>
</html>